//
//  ViewController.m
//  Bluetooth1
//
//  Created by 张飞跃 on 16/5/24.
//  Copyright © 2016年 冰泪. All rights reserved.
//

#import "ViewController.h"
#import "MyCell.h"


@interface ViewController ()
{
    UIAlertView *mAlertView;
    CBPeripheral *p;
    CBCharacteristic *c;
    NSDictionary *options;
}
@property (nonatomic,strong)CBCentralManager *centralManager;
@property (nonatomic,strong)NSMutableArray *dataSource;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataSource = [[NSMutableArray alloc]init];
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    [btn setTitle:@"扫描蓝牙" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor redColor];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [btn addTarget:self action:@selector(startScan:) forControlEvents:UIControlEventTouchUpInside];
    

    self.navigationItem.leftBarButtonItem = item;
    
    UIButton *btn1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    [btn1 setTitle:@"停止扫描" forState:UIControlStateNormal];
    btn1.backgroundColor = [UIColor redColor];
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithCustomView:btn1];
    [btn1 addTarget:self action:@selector(stopScan:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = item1;


    //初始化
   self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    //扫描外设
   // [manager scanForPeripheralsWithServices:nil options:options];
    
 }
- (void)startScan:(id)sender {//开始扫描
    NSLog(@"开始扫描");
    [self.dataSource removeAllObjects];
    
    [self.centralManager scanForPeripheralsWithServices:nil options:nil];//表示扫描所有外设
    //[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"FFE0"]] options:nil];//扫描匹配服务号的蓝牙
}

- (void)stopScan:(id)sender {//停止扫描
     NSLog(@"停止扫描");
    [self.centralManager stopScan];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSString * state = nil;
    
    switch ([central state])
    {
        case CBCentralManagerStateUnsupported://不支持蓝牙
            state = @"不支持蓝牙";
            break;
        case CBCentralManagerStateUnauthorized://没有蓝牙授权
            state = @"没有蓝牙授权";
            break;
        case CBCentralManagerStatePoweredOff://蓝牙关闭
            state = @"蓝牙关闭";
            break;
        case CBCentralManagerStatePoweredOn://蓝牙打开
            state = @"蓝牙已经打开";
            break;
        case CBCentralManagerStateUnknown:
        default:
            ;
    }
    
    NSLog(@"当前状态: %@", state);
}
#pragma mark  //找到设备之后将回调
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
     NSLog(@"找到蓝牙设备");
    //peripheral代表你发现的设备，advertisementData时广告数据，rssi代表着信号强度.
//
    NSString *str = [NSString stringWithFormat:@"peripheral: %@ rssi: %@, advertisementData: %@ ", peripheral, RSSI, advertisementData];
    NSLog(@"%@",str);
    
    
    [self.dataSource addObject:peripheral];
    NSArray *arr = [NSArray arrayWithArray:self.dataSource];
    NSSet *set = [NSSet setWithArray:arr];
   // NSLog(@"set%@\n", set);
    
    
    
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:[set allObjects]];
    [self.tableView reloadData];
    
}
#pragma mark  连接上蓝牙之后回调
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"已经连接蓝牙: %@", peripheral);
    mAlertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"蓝牙连接成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [mAlertView show];

    peripheral.delegate = self;
    [central stopScan];
    [peripheral discoverServices:nil];//nil 这个方法也是传入nil返回所有服务，如果是传入特定的服务id,只返回该服务 这里我们传入nil来返回所有服务
    //[peripheral discoverServices:@[[CBUUID UUIDWithString:@"FFE0"]]]
}

//已经获取到的服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error)
    {
        NSLog(@"Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
        return;
    }
    
    for (CBService *service in peripheral.services)
    {
        NSLog(@"蓝牙对应的Service UUID: %@", service.UUID);
        if ([service.UUID isEqual:[CBUUID UUIDWithString:@"FEE0"]])
        {
            [peripheral discoverCharacteristics:nil forService:service];//因为需要FFE0,所以让该服务返回对应的characteristics.
        }
    }
}
//解析获取到的服务特征
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{//这里的只有一个特征  也就是FFE0写服务的写特征. 获取到该特征。进行写服务，
    if (error)
    {
        NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
        return;
    }
    for (CBCharacteristic * characteristic in service.characteristics)
    {
        NSLog(@"characteristic：：：%@",characteristic);
        if( [characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FEE0"]])
        {
            p = peripheral;
            c = characteristic;
            
            //[testPeripheral readValueForCharacteristic:characteristic];
            NSLog(@"找到需要的设备了");
            mAlertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"设备获取完成可以进行数据交互" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
         
            [mAlertView show];
            /*
             //蓝牙交互时候写法
             NSString *RStr = @"2764";
             NSMutableString *str = [NSMutableString new];
             [str appendFormat:@"%c", 28];
             [str appendFormat:@"%c", 33];
             [str appendFormat:@"%c", 8];
             
             [self.p writeValue:[str dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)] forCharacteristic:self.c type:CBCharacteristicWriteWithResponse];
             RStr = @"吴水凤 你好呀!!!\n\n\n\n\n\n\n\n";
             [self.p writeValue:[RStr dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)] forCharacteristic:self.c type:CBCharacteristicWriteWithResponse];
             
             补充： 如果该特征是可以读特征，你可以对该特征进行订阅。
             
             [peripheral setNotifyValue:YES forCharacteristic:interestingCharacteristic];
             
             该方法回调peripheral:didUpdateValueForCharacteristic:error:方法
             */
        }
    }
}
#pragma mark  tableVIew相关


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
    if (nil == cell) {
        cell = [[MyCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:@"MyCell"];
    }
    /*
       "<CBPeripheral: 0x14d548d30, identifier = 6CD10499-246F-A3DC-CA2C-B79A162C0FE9, name = MI1S, state = disconnected>",
     */
   // NSLog(@"%@",_dataSource);
    CBPeripheral *cbp = _dataSource[indexPath.row];
    //NSLog(@"%@",cbp.name);
    cell.titlesLabel.text = [NSString stringWithFormat:@"名字:%@        状态:%ld\n  identifier:%@\n",cbp.name,(long)cbp.state,cbp.identifier];
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //点击之后连接蓝牙
       [self.centralManager connectPeripheral:self.dataSource[indexPath.row]  options:nil];
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",indexPath.row);
    //断开连接
     [self.centralManager cancelPeripheralConnection:self.dataSource[indexPath.row]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
